package com.febers.ihealth.utils

import com.febers.ihealth.MyApp
import jxl.Workbook
import kotlin.reflect.full.memberProperties

object AnalyzeUtil {

    /**
     * 第一行是药物的列表，
     * 第一列是症状，
     * 遍历xls得到 map<症状, 药物>，然后通过反射的方式得到user的症状属性list，
     * 遍历list，从map中get药物，添加到最后的结果map中
     */
    fun analysis(): List<String> {
        val medicineList: MutableList<String> = ArrayList()
        val illnessList: MutableList<String> = ArrayList()
        val positionMap: MutableMap<Int, Int> = HashMap()
        val positionMap2: MutableMap<Int, MutableList<Int>> = HashMap()

        val workbook = try {
            Workbook.getWorkbook(MyApp.context().assets.open("relations.xls"))
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
        workbook ?: return emptyList()

        val sheets = workbook.sheets
        log {
            "sheet name: ${sheets[0]} and ${sheets[1]}"
        }
        log { "=========开始遍历表sheet========" }
        val sheet = sheets[0]
        val rows = sheet.rows //行
        val columns = sheet.columns //列
        var row = 0
        while (row < rows) {
            var column = 0
            while (column < columns) {
                val cell = sheet.getCell(column, row)
                if (row == 0) {
                    if (column>0) { //第一行第一列不需要
                        medicineList.add(cell.contents)
                    }
                }
                if (column == 0) {
                    if (row>0) {    //第一列第一行不需要
                        illnessList.add(cell.contents)
                    }
                }
                if (row > 0 && column > 0 && cell.contents.isNotEmpty()) {
                    positionMap[row-1] = column-1
                    if (positionMap2.containsKey(row-1)) {
                        positionMap2.get(row-1)?.add(column-1)
                    } else {
                        positionMap2[row-1] = arrayListOf(column-1)
                    }
//                    log { "存在匹配的结果,位置为：[${row-1}][${column-1}]" }
                }
                column++
            }
            row++
        }
        log {
            "药物总数: ${medicineList.size} 症状总数: ${illnessList.size} 关系总数: ${positionMap.size}"
        }

        //反射获取user症状
        val members = user.javaClass.kotlin.memberProperties.filter {
            it.returnType.toString() == "kotlin.Boolean"
        }

        val resultList: MutableList<String> = ArrayList()
        val resultMap: MutableMap<String, MutableList<String>> = HashMap()
        members.forEach {
//            log {  "属性名称: ${it.name} | ${it.returnType}" }
            if (it.get(user) as? Boolean == true) {
                log {  "为true的属性名称: ${it.name}" }
                for (illness in illnessList) {
                    if (illness == it.name) {
                        val key = illnessList.indexOf(illness)
                        if (positionMap2.containsKey(key)) {
                            positionMap2.get(key)?.forEach { column ->
//                                log {  "========位置结果：行: $row : 列: $column =======" }
                                if (resultMap.containsKey(illnessList[key])) {
                                    resultMap[illnessList[key]]?.add(medicineList[column])
                                } else {
                                    resultMap[illnessList[key]] = arrayListOf(medicineList[column])
                                }
                                resultList.add(medicineList[column])
                            }
                        }
                    }
                }
            }
        }

        if (user.fluTimes.toInt() > 5) {
            //玉屏风颗粒，参苏丸、感冒片
            resultList.add("玉屏风颗粒")
            resultList.add("参苏丸")
            resultList.add("感冒片")
        }
        //恶风、汗出、苔薄白，鼻塞，流涕、咳嗽，咽痛
        var count = 0
        if (user.eFeng) count++
        if (!user.wuhan) count++
        if (user.shetaibai) count++
        if (user.bise) count++
        if (user.bitiBai || user.bitiQing || user.bitiHuang) count++
        if (user.kesou) count++
        if (user.yantong) count++
        if (count > 2) {
            resultList.addAll(listOf("桂枝颗粒（合剂）", "荆防败毒丸", "感冒清热颗粒", "桑菊感冒片",
                "银翘解毒丸", "风热感冒颗粒"))
        }
        if (user.yanzhongEhan && user.wuhan) {
            resultList.addAll(listOf("感冒清热颗粒","风寒感冒颗粒","通宣理肺丸","小青龙合剂","伤风停胶囊",
                "九味羌活丸","荆防败毒丸","藿香正气水","止嗽定喘丸（麻杏石甘）","防风通圣丸"))
        }
        count = 0
        if (user.fare) count++
        if (user.bitiHuang || user.bitiBai) count++
        if (user.ketanHuangchou) count++
        if (user.yangan || user.yantong) count++
        if (user.shebianjianhong) count++
        if (user.maishu) count++
        if (count>2) {
            resultList.addAll(listOf("桑菊感冒片","银翘解毒丸","风热感冒颗粒","连花清瘟胶囊","抗病毒口服液",
                "双黄连","板蓝根","小儿肺热咳喘冲剂"))
        }
        count = 0
        if (user.youhan) count++
        if (user.fare) count++
        if (user.xinfan) count++
        if (count>1) {
            resultList.addAll(listOf("祛暑丸","暑湿感冒冲剂","清暑益气丸","清凉防暑颗粒","暑热感冒颗粒"))
        }
        count = 0
        if (user.shenzhong || user.guanjietengtong || user.jingxiangtengtong || user.jiroutengtong || user.shentongwuzhiwei) count++
        if (user.toutong || user.touzhong) count++
        if (user.shiyucha || user.wushiyu) count++
        if (user.shetaihou || user.shetaini) count++
        if (user.exin) count++
        if (count > 2) {
            resultList.addAll(listOf("小青龙合剂","九味羌活丸","藿香正气水","暑湿感冒冲剂"))
        }
        count = 0
        if (user.toutong||user.yangan||user.yantong) count++
        if (user.wutanGanke) count++
        if (user.biganBizao) count++
        if (user.kouganbuyuyin) count++
        if (user.shebianjianhong) count++
        if (user.shetaishao) count++
        if (count>2) {
            resultList.addAll(listOf("秋燥感冒冲剂","杏苏散"))
        }
        return findMostMedicines(resultList)
    }

    private fun findMostMedicines(list: List<String>): List<String> {
        val result: MutableList<String> = ArrayList()
        fun mostInMap(map: Map<String, Int>, count: Int) {
            result.clear()
            map.keys.forEach {
                if (map[it] ?: error("") > count) {
                    result.add(it)
                    log { "数量超过 $count 的药品: $it" }
                }
            }
        }

        val countMap: MutableMap<String, Int> = HashMap()
        list.forEach {
            if (countMap.containsKey(it)) {
                countMap[it] = countMap[it]!!+1
            } else {
                countMap[it] = 1
            }
        }
        var count = 1
        do {
            count += 1
            mostInMap(countMap, count)
        } while (result.size > 5 && count < list.size)  //只要结果的药物超过5种以及出现次数小于入参链表长度
        return result
    }
}